﻿using MvvmCross.Platform;
using MvvmCross.Plugins.Messenger;
using Sidvall.WorkItemManager.UI.Messaging;

namespace Sidvall.WorkItemManager.UI.ViewModels
{
	public partial class IntervalRetryPolicyViewModel
	{
		#region Public Members

		#region Context

		private string _Context;
		public string Context
		{
			get
			{
				return _Context;
			}
			set
			{
				if (_Context == value)
					return;
				_Context = value;
				RaisePropertyChanged("Context");
				OnContextChanged();
			}
		}

		#endregion

		#region OnActiveEntityChanged

		protected override void OnActiveEntityChanged(Sidvall.Business.BusinessObjectChangeMode changeMode, Sidvall.Business.ChildChangedEventArgs childArgs, System.ComponentModel.PropertyChangedEventArgs propertyArgs)
		{
			this.Context = Sidvall.WorkItemManager.UI.Entities.IntervalRetryPolicy.Serialize(this.ActiveEntity);
		}

		#endregion
		#region OnContextChanged

		protected void OnContextChanged()
		{
			if (this.PublishChange)
			{
				var messenger = Mvx.Resolve<IMvxMessenger>();
				var message = new WorkItemRetryPolicyContextMessage(this)
				{
					Context = this.Context,
				};
				messenger.Publish<WorkItemRetryPolicyContextMessage>(message);
			}
		}

		#endregion

		#region Init

		public void Init(ContextParameter item)
		{
			this.ContextParameter = item;
		}

		#endregion
		#region Start

		public override void Start()
		{
			var messenger = Mvx.Resolve<IMvxMessenger>();
			this.ViewModelResources.Add(messenger.Subscribe<WorkItemRetryPolicyContextMessage>(OnWorkItemRetryPolicyContextMessage));

			if (this.ContextParameter != null)
			{
				this.PublishChange = false;
				this.Context = this.ContextParameter.Context;
				this.PublishChange = true;
				this.ActiveEntity = Sidvall.WorkItemManager.UI.Entities.IntervalRetryPolicy.Deserialize(this.Context);
				this.ContextParameter = null;
			}
		}

		#endregion

		#endregion
		#region Private Members

		private ContextParameter ContextParameter { get; set; }
		private bool PublishChange { get; set; }

		#region OnWorkItemRetryPolicyContextMessage

		private void OnWorkItemRetryPolicyContextMessage(WorkItemRetryPolicyContextMessage item)
		{
			if (this.Context == item.Context)
				return;
			this.PublishChange = false;
			this.Context = item.Context;
			this.PublishChange = true;
			this.ActiveEntity = Sidvall.WorkItemManager.UI.Entities.IntervalRetryPolicy.Deserialize(this.Context);
		}

		#endregion

		#endregion
	}
}